package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoimpl implements UserDao {
    @Override
    public List<User> findAll() {
        //jdbc 操作
        //创建集合
        List<User> users =new ArrayList<>();
        ResultSet  resultSet=null;
        PreparedStatement preparedStatement=null;
        Connection connection=null;


        //jdbc操作数据库 查询
//1.加载驱动

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2.获取链接(url username password)
            String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
             connection = DriverManager.getConnection(url, "root", "319257rj");
            //if (connection != null) {
            //    System.out.println("连接成功");
            //}
            //3.写sql语句
            String sql = "select * from user";
            //4.预编译sql
             preparedStatement = connection.prepareStatement(sql);
            //5.如果有参数设置参数

            //6.执行sql语句
             resultSet = preparedStatement.executeQuery();
            //7.遍历结果集
            while (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getInt(1));
                user.setName(resultSet.getString(2));
                user.setPassword(resultSet.getString(3));
                users.add(user);
            }
            return users;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //8.关闭资源

            try {

                if(resultSet !=null){
                    resultSet.close();
                }
                if(preparedStatement !=null){
                    resultSet.close();
                }

                if(connection !=null){
                    resultSet.close();
                }
            }catch (SQLException e){
                throw new RuntimeException(e);
            }
        }
    }

}




